'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Layout from '../../components/Layout';
import { useAuth } from '../../contexts/AuthContext';
import { IconLoader2, IconArrowLeft } from '@tabler/icons-react';

interface UserProfile {
  name: string | null;
  email: string;
  age: number | null;
  gender: string | null;
  height: number | null;
  weight: number | null;
  healthGoal: string | null;
}

export default function EditProfile() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/login?redirect=/profile/edit');
      return;
    }

    if (user) {
      fetch('/api/user/profile', { credentials: 'include' })
        .then(res => res.json())
        .then(data => {
          setProfile(data.profile);
          setLoading(false);
        })
        .catch(error => {
          console.error('获取用户资料失败:', error);
          setError('获取用户资料失败');
          setLoading(false);
        });
    }
  }, [user, authLoading, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError('');

    try {
      const res = await fetch('/api/user/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(profile),
        credentials: 'include',
      });

      if (!res.ok) {
        throw new Error('保存失败');
      }

      router.push('/profile');
    } catch (error) {
      console.error('保存用户资料失败:', error);
      setError('保存失败，请稍后重试');
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (field: keyof UserProfile, value: string | number | null) => {
    setProfile(prev => {
      if (!prev) return prev;
      return { ...prev, [field]: value };
    });
  };

  if (loading) {
    return (
      <Layout>
        <div className="flex justify-center items-center min-h-[60vh]">
          <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="max-w-6xl mx-auto">
        <div className="bg-white p-8">
          <div className="flex items-center gap-4 mb-8">
            <button
              onClick={() => router.back()}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <IconArrowLeft className="w-5 h-5" />
            </button>
            <h1 className="text-2xl font-bold">编辑个人资料</h1>
          </div>

          {error && (
            <div className="bg-red-50 text-red-600 p-4 rounded-lg mb-6">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="max-w-2xl space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                邮箱
              </label>
              <input
                type="email"
                value={profile?.email || ''}
                disabled
                className="w-full px-4 py-2 border rounded-lg bg-gray-50"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                姓名
              </label>
              <input
                type="text"
                value={profile?.name || ''}
                onChange={e => handleChange('name', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="请输入姓名"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                性别
              </label>
              <select
                value={profile?.gender || ''}
                onChange={e => handleChange('gender', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">请选择性别</option>
                <option value="male">男</option>
                <option value="female">女</option>
                <option value="other">其他</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                年龄
              </label>
              <input
                type="number"
                value={profile?.age || ''}
                onChange={e => handleChange('age', e.target.value ? parseInt(e.target.value) : null)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="请输入年龄"
                min="1"
                max="120"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                身高 (cm)
              </label>
              <input
                type="number"
                value={profile?.height || ''}
                onChange={e => handleChange('height', e.target.value ? parseInt(e.target.value) : null)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="请输入身高"
                min="1"
                max="300"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                体重 (kg)
              </label>
              <input
                type="number"
                value={profile?.weight || ''}
                onChange={e => handleChange('weight', e.target.value ? parseInt(e.target.value) : null)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="请输入体重"
                min="1"
                max="500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                健康目标
              </label>
              <select
                value={profile?.healthGoal || ''}
                onChange={e => handleChange('healthGoal', e.target.value)}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">请选择健康目标</option>
                <option value="weight_loss">减重</option>
                <option value="muscle_gain">增肌</option>
                <option value="maintenance">保持健康</option>
                <option value="better_diet">改善饮食习惯</option>
              </select>
            </div>

            <div className="pt-4">
              <button
                type="submit"
                disabled={saving}
                className="w-full btn-primary flex items-center justify-center gap-2"
              >
                {saving && <IconLoader2 className="w-5 h-5 animate-spin" />}
                {saving ? '保存中...' : '保存修改'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </Layout>
  );
} 